package com.gitee.wsl.ext.collection

import kotlin.reflect.KType

/**
 * Calls the [selector] function for each value in the collection and returns the sum of the produced values.
 */
inline fun <T> Iterable<T>.sumOf(selector: (T) -> Float): Float {
    var sum = 0f
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

inline fun <T> Iterable<T>.sumOf(selector: (T) -> Long): Long {
    var sum = 0L
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

@PublishedApi
internal fun <T, R : Number> Iterable<T>.sumOf(type: KType, selector: (T) -> R?): R {
    if (type.isMarkedNullable) {
        val seq = asSequence().mapNotNull(selector).asIterable()
        return seq.sum(type)
    }
    return when (type.classifier) {
        Double::class -> sumOf(selector as ((T) -> Double)) as R
        Int::class -> sumOf(selector as ((T) -> Int)) as R
        Long::class -> sumOf(selector as ((T) -> Long)) as R
        //BigDecimal::class -> sumOf(selector as ((T) -> BigDecimal)) as R
        else -> TODO()
    }
}

/*
@PublishedApi
internal fun Iterable<BigDecimal>.sum(): BigDecimal {
    var sum: BigDecimal = BigDecimal.ZERO
    for (element in this) {
        sum += element
    }
    return sum
}

@PublishedApi
internal fun Sequence<BigDecimal>.sum(): BigDecimal {
    var sum: BigDecimal = BigDecimal.ZERO
    for (element in this) {
        sum += element
    }
    return sum
}*/
